<template>
  <div style="font-size: 12px; margin-top: 5px;">
    仅保留前
    <a-input-number
      v-model="inputValue"
      type="number"
      size="small"
      :min="1"
      :max="calcMaxRows"
      step="1"
      :formatter="(inputValue) => Number.parseInt(inputValue)"
      @change="onChange"
    />
    行的数据
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { IColumn, IKeyValueStore } from '@/store/modules/dataview'
import { StatisticsAction } from '@/util/data-selection-actions'
import { apiGetTableData } from '@/api/data-clean'

@Component
export default class FilterSaveTopnRow extends Vue {
  @Prop() requestParams: any
  @Prop() column!: IColumn
  @Prop() editData!: any
  @Prop({ default: false }) isEdit!: boolean
  @Prop({ default: '' }) parentTableName!: boolean
  @Prop({ default: 0 }) rowCount!: number
  private inputValue = ''
  private lastHistoryRowCount: number = 0

  mounted() {
    this.onChange()
  }

  private get calcMaxRows() {
    return this.isEdit ? this.lastHistoryRowCount : this.rowCount
  }

  @Watch('editData', { immediate: true, deep: true })
  private onCurrentHistory(newValue: IKeyValueStore) {
    if (!newValue || !this.isEdit) {
      return
    }
    const history = newValue.data
    // todo
    if (
      history.actionType === StatisticsAction.filterSaveTopnRow &&
      history.col === this.column.name
    ) {
      this.inputValue = history.topN
      this.getLastHistoryRowCount()
    }
  }

  // 编辑模式下查询上一个历史节点的行数
  async getLastHistoryRowCount() {
    const requestParameters = this.requestParams || {}
    const response = await apiGetTableData({
      data: {
        curPage: 1,
        name: '_record_id_', // 如果没有字段，那就固定传 _record_id_
        pageSize: 50,
        filter: [],
        table: this.parentTableName, // 查询数据的表名取决于当前历史记录的表名
        taskId: requestParameters.taskId,
      },
    })
    if (!response.data.success) {
      return
    }
    const { result } = response.data
    this.lastHistoryRowCount = result.page.totalElements
  }

  private onChange() {
    this.$emit('on-filter-params-change', {
      data: {
        action: 'TRANSFORM_LIMIT',
        col: this.column.name,
        topN: this.inputValue,
        description: `截取前${this.inputValue}行的数据`,
        actionType: StatisticsAction.filterSaveTopnRow,
      },
    })
  }
}
</script>
